package com.wtwd.device.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.device.constant.Constants;
import com.wtwd.device.constant.RespCode;
import com.wtwd.device.dao.DialMapper;
import com.wtwd.device.dao.SysRoleMapper;
import com.wtwd.device.model.entity.DialManagement;
import com.wtwd.device.model.entity.SysRole;
import com.wtwd.device.model.entity.SysUser;
import com.wtwd.device.model.vo.RespEntity;
import com.wtwd.device.service.DeviceInfoService;
import com.wtwd.device.service.DialService;
import com.wtwd.device.service.GroupInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author mjy
 * @date 2021/08/07
 * @description
 */
@Service
public class DialServiceImpl implements DialService {

    @Value("${file.http}")
    private String fileHttp;
    @Value("${dial.preview.image}")
    private String previewImg;
    @Value("${dial.file}")
    private String dialFile;
    @Autowired
    private DialMapper dialMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Resource
    private GroupInfoService groupInfoService;


    @Override
    public RespEntity getDialListByConditions(Integer currentPage, Integer pageSize, HashMap<Object, Object> searchMap, SysUser sysUser) {
        SysRole sysRole = sysRoleMapper.getSysRoleByRoleId(sysUser.getRoleId());
        IPage<DialManagement> dialManagements = null;
        if (sysRole.getRoleType().equals(Constants.SYS_USER_ROLE_TYPE_CUSTOMER)) {
           /* //1.权限暂时写死，客户无此功能
            //如果说他有这个权限他只能看到他自己的,手表id可以有多个,需求要求只要有就需要展示----只要包含一个就展示
            List<String> watchIds = deviceInfoService.getWatchIdByGroupByCustomerId(sysUser.getCustomerId());
            //条件获取所有符合要求的表盘
            List<DialManagement> dialList = dialMapper.getDialListByConditions(searchMap);
            Iterator<DialManagement> iterator = dialList.iterator();
            while (iterator.hasNext()){
                DialManagement dial = iterator.next();
                String ids = dial.getWatchIds();
                List<String> idList = (List<String>) Arrays.asList(ids.split(","));//表盘里面只要包含就展示
                //定义是否展示标志
                boolean flag=false;
                if (watchIds!=null&&watchIds.size()>0){
                 aa:   for (String id : idList) {
                        for (String watchId : watchIds) {
                            if (StringUtils.isBlank(watchId)||StringUtils.isBlank(id)){
                                continue;
                            }else if (watchId.equals(id)){
                                flag=true;
                                break aa;
                            }
                        }
                    }
                }
                if (!flag){
                    iterator.remove();
                }
            }
            //数据赛选完后分页
            Map<String, Object> restMap = disposalData(dialList, currentPage, pageSize);
            return new RespEntity(RespCode.NO_PERMISSION,restMap);*/
            return new RespEntity(RespCode.NO_PERMISSION);
        } else {
            IPage<Object> page = new Page<>(currentPage, pageSize);
            dialManagements = dialMapper.getDialListByConditions(searchMap, page);
            dialManagements.getRecords().forEach(e -> {
                String url = fileHttp.concat(previewImg.concat(e.getPreviewImg()));
                e.setPreviewImg(url);
                String fileUrl = fileHttp.concat(dialFile.concat(e.getDialFile()));
                e.setDialFile(fileUrl);
            });
        }
        HashMap<String, Object> restMap = new HashMap<>();
        restMap.put("total", dialManagements.getTotal());
        restMap.put("list", dialManagements.getRecords());
        return new RespEntity(RespCode.SUCCESS, restMap);
    }

    @Override
    public RespEntity addDial(DialManagement dialManagement, SysUser sysUser) {
        //鉴别表盘id是否是否重复
        DialManagement dialManagement1 = dialMapper.getDialByDialId(dialManagement.getDialId());
        if (dialManagement1 != null) {
            return new RespEntity(RespCode.DIAL_PLATE_EXIST);
        }
        dialManagement.setUpdateTime(new Date().getTime());
        SysRole sysRole = sysRoleMapper.getSysRoleByRoleId(sysUser.getRoleId());
        if (sysRole.getRoleType().equals(Constants.SYS_USER_ROLE_TYPE_CUSTOMER)) {
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        //校验添加的手表id是否正确
        String watchIds = dialManagement.getWatchIds();
        String[] split = watchIds.split(",");
        List<String> watchIdList = Arrays.asList(split);
        if (watchIdList == null && watchIdList.size() == 0) {
            return new RespEntity(RespCode.NO_PARAM);
        }
        //校验手表id是否正确
        Boolean flag = deviceInfoService.checkWatchIdList(watchIdList);
        if (!flag) {
            return new RespEntity(RespCode.ERROE_WATCHID);
        }
        Integer rest = dialMapper.addDialManagement(dialManagement);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    @Override
    public RespEntity deleteDial(Integer id) {
        Integer rest = dialMapper.deleteDial(id);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    @Override
    public RespEntity updateDial(DialManagement dialManagement, SysUser sysUser) {
        //鉴别修改后的表盘id(除开自己本身)是否重复
        DialManagement dialManagement1 = dialMapper.getDialByDialId(dialManagement.getDialId());
        if (dialManagement1 != null) {
            if (!dialManagement1.getId().equals(dialManagement.getId())) {
                return new RespEntity(RespCode.DIAL_PLATE_EXIST);
            }
        }
        dialManagement.setUpdateTime(new Date().getTime());
        SysRole sysRole = sysRoleMapper.getSysRoleByRoleId(sysUser.getRoleId());
        if (sysRole.getRoleType().equals(Constants.SYS_USER_ROLE_TYPE_CUSTOMER)) {
            //只能添加自己拥用的设备id,需要校验
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        //校验添加的手表id是否正确
        String watchIds = dialManagement.getWatchIds();
        String[] split = watchIds.split(",");
        List<String> watchIdList = Arrays.asList(split);
        if (watchIdList == null && watchIdList.size() == 0) {
            return new RespEntity(RespCode.NO_PARAM);
        }
        //去重
        watchIdList = watchIdList.stream().distinct().collect(Collectors.toList());
        Boolean flag = deviceInfoService.checkWatchIdList(watchIdList);
        if (!flag) {
            return new RespEntity(RespCode.ERROE_WATCHID);
        }
        Integer rest = dialMapper.updateDial(dialManagement);
        groupInfoService.synchronizationGroupDial(dialManagement.getId(), watchIdList);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    @Override
    public List<DialManagement> getDialManagementByWatchId(String watchId) {
        List<DialManagement> dialManagements = dialMapper.getDialManagementByLikeWatchId(watchId);
        if (dialManagements!=null&&dialManagements.size()>0){
            dialManagements= dialManagements.stream().filter(e -> {
                String watchIds = e.getWatchIds();
                String[] split = watchIds.split(",");
                List<String> watchList = Arrays.asList(split);
                if (watchList.contains(watchId)) {
                    return true;
                } else {
                    return false;
                }
            }).collect(Collectors.toList());
        }
        return dialManagements;
    }



    public <T> Map<String, Object> disposalData(List<T> list, Integer curPage, Integer pageSize) {
        List<T> resultRecord = new ArrayList<>();
        if (curPage <= 0) {
            curPage = 1;
        }
        Integer total = 0;
        if (list != null) {
            total = list.size();
        }
        int start = (curPage - 1) * pageSize;
        int end = start + pageSize;
        if (list.size() < start) {
            return null;
        }
        for (int i = start; i < (list.size() < end ? list.size() : end); i++) {
            resultRecord.add(list.get(i));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("list", resultRecord);
        return map;
    }


}